package com.fxwater.websocket.init;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.fxwater.websocket.domain.ScheduledTask;
import com.fxwater.websocket.service.IScheduledTaskService;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Description:
 * @Author: 王明朝
 * @Date: 2019/6/26 14:27
 */
@Component
public class ScheduledTaskInitializer<InitEvent>  implements ApplicationListener{

    @Autowired
    private IScheduledTaskService scheduledTaskService;

    /**
     * 日志组件
     */
    private Logger logger =  LoggerFactory.getLogger(ScheduledTaskInitializer.class);

    private final AtomicBoolean SCHEDULED_TASK_STARTED = new AtomicBoolean(false);


    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        synchronized (SCHEDULED_TASK_STARTED){
            if(!SCHEDULED_TASK_STARTED.getAndSet(true)){
                logger.info("----------------------------------------系统启动，加载任务调度----------------------------------------");
                List<ScheduledTask> scheduledTasks = scheduledTaskService.listScheduledTask();
                SchedulerFactory factory = new StdSchedulerFactory();
                if(CollectionUtil.isNotEmpty(scheduledTasks)){
                    scheduledTasks.sort(Comparator.comparingInt(ScheduledTask::getTaskOrder));
                    scheduledTasks.forEach(scheduledTask -> {
                        try{
                            String className = scheduledTask.getTaskClass();
                            if(StrUtil.isNotEmpty(className) && StrUtil.isNotEmpty(scheduledTask.getTaskCron())){
                                logger.info("【任务调度】开始启动任务调度，任务名称：{}，任务详情：{}，任务执行组件:{},执行频率：{}"
                                        ,scheduledTask.getTaskName()
                                        ,scheduledTask.getRemark()
                                        ,className
                                        ,scheduledTask.getTaskCron());
                                Class<? extends Job> clazz = (Class<? extends Job> ) Class.forName(className);
                                JobDetail jobDetail = JobBuilder.newJob(clazz)
                                        .withIdentity(scheduledTask.getTaskName(), scheduledTask.getTaskName())
                                        .build();
                                Trigger trigger = TriggerBuilder
                                        .newTrigger()
                                        .withIdentity(scheduledTask.getTaskName(), scheduledTask.getTaskName())
                                        .startNow()
                                        .withSchedule(CronScheduleBuilder.cronSchedule(scheduledTask.getTaskCron()))
                                        .build();

                                Scheduler scheduler = factory.getScheduler();
                                scheduler.scheduleJob(jobDetail,trigger);
                                scheduler.start();
                                logger.info("【任务调度】任务调度名称\"{}\"已启动",scheduledTask.getTaskName());
                            }
                        }catch (Exception e){
                            logger.info(e.getMessage());
                        }
                    });
                }
                logger.info("----------------------------------------系统启动，加载完成任务调度----------------------------------------");
            }
        }

    }




}
